package com.hanyoujia.http;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;


/**
 * @description: TODO 类描述
 * @author: hanyoujia
 * @data 2021/7/28 19:04
 */
public class HttpClientTest {


    /**
     * @param:
     * @description: 使用HttpClient发起无参的get请求。包含请求头、请求返回状态码、响应请求头的处理
     * @return: void
     * @author: hanyoujia
     * @date: 2021/7/28
     */
    @Test
    public void test(){
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://www.baidu.com/");
        //解决Httpclient被认为不是真人行为。
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //防盗链,URL要是发生防盗链的网站的URL
        httpGet.addHeader("Referer", "https://www.baidu.com/");

        CloseableHttpResponse response = null;

        try {
            response = closeableHttpClient.execute(httpGet);

            //状态码，代表本次请求的成功、失败的状态
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){

                //响应头
                Header[] allHeaders = response.getAllHeaders();
                for(Header header : allHeaders){
                    System.out.println("相应头" + header.getName() + "的值" + header.getValue());
                }



                //HttpEntity不仅可以作为结果，也可以做位请求的参数实体，有很多实现
                HttpEntity httpEntity = response.getEntity();

                System.out.println("ContentType:" + httpEntity.getContentType());

                String toStringResult = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println(toStringResult);

                EntityUtils.consume(httpEntity);
            }else{
                System.out.println("响应失败，状态码" + statusLine.getStatusCode());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null){
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
